<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\AdminLog;
use app\api\model\v1\DutyUnit;
use app\api\validate\v1\AdminValidate;
use app\api\validate\v1\UnitValidate;
use app\BaseController;
use think\exception\ValidateException;
use think\Request;

class DutyUnitCon extends BaseController
{


    use SearchDataForModel;

    /**
     * @User: 刘海龙
     * @Date: 2021/11/16
     * @Time: 11:04
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 数据源-列表
     */
    public function dutyUnitList(){
        $limit = $this->request->param('limit',10);
        $res = $this->search(new DutyUnit(),[],$limit);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/16
     * @Time: 11:23
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存and编辑
     */
    public function saveDutyUnit(){
        $id = $this->request->param('id', 0);
        $data = $this->request->param();
        try {
            $validator = $this->validate($this->request->param(),
                UnitValidate::rules($id),
                UnitValidate::msg());
            if ($validator){
                if (intval($id) === 0) {
                    DutyUnit::create($data);
                } else {
                    $unit = DutyUnit::find($id);
                    $unit->update($data);

                }
                AdminLog::record(intval($id) === 0 ? '新增责任单位' : '编辑责任单位', $this->request->param(), $this->request->uid, $this->request->username);
                return $this->response();
            }
        }catch (ValidateException $exception){
            return $this->response(403,$exception->getError());
        }
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/11/16
     * @Time: 11:30
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 单位删除
     */
    public function unitDelete($id){

        $ids = explode(',', $id);

        foreach ($ids as $id) {
            $unit = DutyUnit::find(intval($id));
            if (is_null($unit)) {
                return $this->response(404, '此单位不存在');
            }
            $unit->force()->delete();
            AdminLog::record('删除单位', $this->request->param(), $this->request->uid, $this->request->username);
        }
        return $this->response();
    }
}
